package mastermind.gui.actions;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import mastermind.gui.RegisterFrame;
import mastermind.socket.protocol;
import mastermind.socket.socketConnect;

public class SendRegisterAction extends AbstractAction{

	private RegisterFrame frame;
	
	public SendRegisterAction(RegisterFrame frame)
	{
		this.frame = frame;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		
		String firstName = frame.getFirstName();
		String surname = frame.getSurname();
		String username = frame.getUsername();
		String password = frame.getPassword();
		String phno = frame.getPhno();
		
		if(firstName.equals("") || surname.equals("") || username.equals("") || password.equals("") || phno.equals(""))
		{
			String msg = "Fill in all fields";
			JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
		}
		else
		{
			socketConnect connect = frame.getSocket();
			DataInputStream dio = connect.getInputStream();
			DataOutputStream dos = connect.getOutputStream();
			
			if(connect != null && dio != null && dos != null)
			{

				try 
				{
					dos.writeInt(protocol.ATTEMPT_REGISTER); //attempt to register
					dos.flush();
					dos.writeUTF(firstName);
					dos.writeUTF(surname);
					dos.writeUTF(username); //send register info
					dos.writeUTF(password);
					dos.writeUTF(phno);

					int response;
	
					while((response = dio.readInt()) != protocol.REGISTER_END)
					{
						if(response == protocol.SEND_REGISTER_INFO)
						{
							dos.writeUTF(firstName);
							dos.writeUTF(surname);
							dos.writeUTF(username); //send register info
							dos.writeUTF(password);
							dos.writeUTF(phno);
						}
						if(response == protocol.REGISTER_FAILED)
						{
							String msg = "Register failed. User may exist";
							JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
						}
						else if(response == protocol.REGISTER_SUCCESS)
						{
							String msg = "Register Successful";
							JOptionPane.showConfirmDialog((Component) null, msg, "Success", JOptionPane.DEFAULT_OPTION);
						}
					}
				} 
				catch (IOException e1) 
				{
					e1.printStackTrace();
				}
			}
			frame.dispose();
		}
	}

}
